<?php

class Backoffice_AsyncController extends CC_Controller
{
    public function init()
    {
        parent::init();
        
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();
    }
    
    public function contactSearchAction()
    {
        $ret = array();
        $user = $this->_helper->userSession();
        $contactService = $this->_serviceLocator->getService('ContactService');
        $contacts = $contactService->findContact($this->_getParam('term'), $user->getId());
        //$contacts = $this->_em->getRepository('CC\Entity\Contact')->findContact($this->_getParam('term'), $user);
        
        foreach($contacts as $contact)
        {
            $tmpContact = new stdClass();
            $tmpContact->name = $contact['name'];
            $tmpContact->email = $contact['email'];
            $tmpContact->isNewContact = false;
            
            $ret[] = $tmpContact;
            unset($tmpContact); // Clear memory
        }
        
        // Add the new contact entry.
        $tmp = new stdClass();
        $tmp->name = 'Add new contact';
        $tmp->email = '';
        $tmp->isNewContact = true;
        $ret[] = $tmp;
        
        unset($tmp); // Clear memory
        
        echo Zend_Json_Encoder::encode($ret);
    }
    
    public function newContactAction()
    {
        $form = new Backoffice_Model_FormNewContact($this->_em);
        $form->setAttrib('id', 'newContactForm');
        
        if($this->getRequest()->isPost())
    	{
    	    if($form->isValid($this->_request->getParams()))
    	    {
                $contactService = $this->_serviceLocator->getService('ContactService');
    	        
    	        $contactDetails = array(
    	            'name' => $form->getValue('name'),
                    'emailAddress' => $form->getValue('email')
    	        );
    	        
    	        $contactCreated = $contactService->addContact($contactDetails, $this->_helper->userSession()->getId());
    	        
    	        if($contactCreated)
    	        {
    	            $res = new stdClass();
    	            $res->success = true;
    	            $res->name = $form->getValue('name');
    	            $res->email = $form->getValue('email');

    	            echo Zend_Json_Encoder::encode($res);
    	        }
    	    }
    	}
        else 
        {
            echo $form;
        }
    }
}

